import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _WebViewState();
}

class _WebViewState extends State<WebViewPage> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  WebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          title: Text("WebView"),
          actions: [
            PopupMenuButton(
                onSelected: (value) {
                  switch (value) {
                    case "baidu":
                      _webViewController.loadUrl("https://m.baidu.com");
                      break;
                    case "ssoonn":
                      _webViewController.loadUrl("http://ssoonn.com");
                      break;
                    case "close":
                      Navigator.of(context).pop();
                      break;
                  }
                },
                itemBuilder: (context) {
                  return <PopupMenuEntry>[
                    PopupMenuItem(
                      child: Text("baidu.com"),
                      value: "baidu",
                    ),
                    PopupMenuItem(
                      child: Text("ssoonn.com"),
                      value: "ssoonn",
                    ),
                    PopupMenuItem(
                      child: Text("关闭"),
                      value: "close",
                    )
                  ];
                },
                icon: Icon(
                  Icons.list,
                  color: Colors.white,
                  size: 24,
                )),
          ],
        ),
        body: Builder(
          builder: (BuildContext context) {
            return WebView(
              initialUrl: "https://m.baidu.com",
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (WebViewController controller) {
                _controller.complete(controller);
                _webViewController = controller;
              },
            );
          },
        ),
      ),
      // ignore: missing_return
      onWillPop: () {
        if (_webViewController != null) {
          _webViewController.canGoBack().then((value) =>
              value ? _webViewController.goBack() : Navigator.pop(context));
        } else {
          Navigator.pop(context);
        }
      },
    );
  }
}
